<!-- 销毁管理 -->
<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('DestoryManagerAdd') > -1" class="doumee_table_header">
      <el-button type="primary" @click="putStorageAdd">新增</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="销毁单号"
        prop="orderId"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        label="商品信息"
        min-width="200"
        prop="type"
      >
        <template slot-scope="scope">
          {{ scope.row.goodsList&& scope.row.goodsList.length > 0?scope.row.goodsList[0].name +'x'+ scope.row.goodsList[0].count: '' }}
          <span style="word-spaceing: 10px" />
          <span style="word-spaceing: 10px" />
          <el-button
            v-if="scope.row.goodsList.length > 1"
            size="small"
            icon="el-icon-more"
            @click="toShowGoodsList(scope.row.goodsList)"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作员"
        prop="creator"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="销毁时间"
        min-width="160"
        show-overflow-tooltip
        prop="createDate"
      />
      <el-table-column
        align="center"
        label="销毁原因"
        prop="info"
        min-width="200"
        show-overflow-tooltip
      />
    </el-table>
    <!-- <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :current-page.sync="pagination.page"
        :total="totalCount"
        @current-change="getList"
      />
    </div> -->
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog
      title="新增"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="750px"
      :visible.sync="showPutStorageAdd"
      :before-close="willClose"
    >
      <div class="add-item">
        <div class="add-item-header">
          <div class="title"><span style="color: red;">* </span>销毁商品：</div>
          <div class="content">
            <el-input
              ref="barcode"
              v-model="addPutSInfo.barCode"
              class="barcode"
              placeholder="条形码，点击扫码获取"
              @input="barcodeChange"
            />
            <el-select
              v-model="addPutSInfo.id"
              class="goods"
              placeholder="选择商品"
              @change="putInfoValueChange"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-input
              v-model="addPutSInfo.count"
              class="num"
              placeholder="销毁数量"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              oninput="if(value<=0) { value = ''}"
            />
            <el-button
              type="primary"
              class="btnitem"
              @click="putAdd()"
            >新增</el-button>
          </div>
        </div>
        <div
          v-for="(item, index) in addGoodsList"
          :key="item.id"
          class="add-item-goods"
        >
          <span class="title"> {{ item.name }}</span>
          <div class="content">
            <el-input v-model="item.barCode" class="barcode" disabled />
            <el-select
              v-model="item.id"
              class="goods"
              placeholder="选择商品"
              @change="addItemValueChange"
            >
              <el-option
                v-for="goods in goodsList"
                :key="goods.id"
                :label="goods.name"
                :value="goods.id"
              />
            </el-select>
            <el-input
              v-model="item.count"
              class="num"
              placeholder="销毁数量"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              oninput="if(value<=0) { value = ''}"
            />
            <el-button
              class="btnitem secondColor"
              @click="deleteItem(index)"
            >删除</el-button>
          </div>
        </div>
        <div class="add-item-footer">
          <span class="title"> 销毁原因：</span>
          <div class="content">
            <el-input
              v-model="remark"
              class="remark"
              placeholder="请输入销毁原因"
            />
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPutStorage">取消</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="confirmPutStorage">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="商品列表"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showMoreGoods"
      :before-close="moreGoodsWillClose"
    >
      <el-table :data="showGoodsList" border fit class="doumee-element-table">
        <el-table-column
          align="center"
          label="商品名称"
          prop="name"
        />
        <el-table-column
          align="center"
          label="商品价格"
          prop="price"
        />
        <el-table-column
          align="center"
          label="销毁数量"
          prop="count"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  inventoryList,
  inventoryAdd,
  queryByBarCode,
  goodsListVenue
} from '@/api'
import { parseTime } from '@/utils'
import QueryForm from '@/components/QueryForm'
import store from '@/store'
export default {
  name: 'DestoryManager',
  components: {
    QueryForm
  },
  data() {
    return {
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: '销毁单号',
          placeholder: '请输入销毁单号',
          clearable: true
        }, {
          filed: 'time',
          type: 'daterange',
          clearable: true
        }],
        online: true
      },
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      totalCount: 0,
      listLoading: true,
      list: [],
      goodsList: [],
      addGoodsList: [],
      showGoodsList: [],
      showMoreGoods: false,
      showPutStorageAdd: false,
      remark: '',
      addPutSInfo: {
        id: '',
        barCode: '',
        count: ''
      },
      putStorageList: [],
      filters: {
        time: []
      },
      pagination: {
        page: 1,
        rows: 10
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
    this.getGoodsListByVenue()
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      filters.venueId = sessionStorage.getItem('venueId')
      filters.type = '3'
      this.listLoading = true
      inventoryList({
        pagination,
        param: {
          ...filters
        },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.totalCount = res.totalCount
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 场馆端商品列表
    getGoodsListByVenue() {
      goodsListVenue({
        param: {
          status: '',
          type: '1',
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.goodsList = res.recordList
        })
        .catch(() => {})
    },
    // 销毁新增操作
    putAdd() {
      if (!this.addPutSInfo.barCode) {
        this.$message.warning('请输入销毁条形码')
        return
      }
      if (!this.addPutSInfo.id) {
        this.$message.warning('请选择要销毁的商品')
        return
      }
      if (!this.addPutSInfo.count) {
        this.$message.warning('请输入要销毁的数量')
        return
      }
      const goods = this.addGoodsList.find(item => item.id === this.addPutSInfo.id)
      if (goods) {
        this.$message.warning('销毁的商品已存在')
        return
      }
      // for (const goods of this.addGoodsList) {
      //   if (goods.id === this.addPutSInfo.id) {
      //     this.$message.warning('销毁的商品已存在')
      //     return
      //   }
      // }
      // const item = JSON.stringify(this.addPutSInfo)
      const goodsinfo = { ...this.addPutSInfo }
      this.addGoodsList.push(goodsinfo)
      this.addPutSInfo = {}
      this.$refs.barcode.focus()
    },
    // 删除销毁商品
    deleteItem(idx) {
      this.addGoodsList.splice(idx, 1)
    },
    // 条形码输入
    barcodeChange(barCode) {
      if (!barCode) {
        return
      }
      queryByBarCode({
        param: {
          barCode: barCode,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          const record = res.record
          if (!record) {
            this.addPutSInfo.barCode = ''
            this.addPutSInfo.id = ''
          } else {
            this.addPutSInfo.id = record.id
            this.addPutSInfo.barCode = record.barCode
          }
        })
        .catch(() => {})
    },
    putInfoValueChange(val) {
      if (!val) {
        return
      }
      if (!this.goodsList) {
        return
      }
      const goods = this.goodsList.find(item => item.id === val)
      if (goods) {
        this.addPutSInfo.barCode = goods.barCode
      }
      // for (const idx in this.goodsList) {
      //   const goods = this.goodsList[idx]
      //   if (goods.id === val) {
      //     this.addPutSInfo.barCode = goods.barCode
      //   }
      // }
    },
    addItemValueChange(val) {
      if (!val) {
        return
      }
      if (!this.goodsList) {
        return
      }
      const goods = this.goodsList.find(item => item.id === val)
      if (!goods) {
        return
      }
      const temp = this.addGoodsList.find(item => goods.id === item.id)
      if (temp) {
        temp.barCode = goods.barCode
      }
      // for (const idx in this.goodsList) {
      //   const goods = this.goodsList[idx]
      //   if (goods.id === val) {
      //     for (const selidx in this.addGoodsList) {
      //       const item = this.addGoodsList[selidx]
      //       if (goods.id === item.id) {
      //         item.barCode = goods.barCode
      //       }
      //     }
      //   }
      // }
    },
    toShowGoodsList(item) {
      this.showGoodsList = item
      this.showMoreGoods = true
    },
    moreGoodsWillClose(done) {
      this.showGoodsList = []
      done()
    },
    clear() {
      this.filters = { time: [] }
      this.getList(1)
    },
    putStorageAdd() {
      this.showPutStorageAdd = true
      setTimeout(() => {
        this.$refs.barcode.focus()
      }, 300)
    },
    cancelPutStorage() {
      this.showPutStorageAdd = false
      this.clearPutStorageInfo()
    },
    willClose(done) {
      this.clearPutStorageInfo()
      done()
    },
    clearPutStorageInfo() {
      this.remark = ''
      this.addGoodsList = []
      this.putStorageList = []
      this.addPutSInfo = {
        id: '',
        barCode: '',
        count: ''
      }
    },
    confirmPutStorage() {
      if (!this.addGoodsList.length) {
        this.$message.warning('请添加销毁商品')
        return
      }
      const goods = this.addGoodsList.find(item => !item.count)
      if (goods) {
        this.$message.warning('请输入销毁的数量')
        return
      }
      // for (const idx in this.addGoodsList) {
      //   const goods = this.addGoodsList[idx]
      //   if (!goods.count) {
      //     this.$message.warning('请输入销毁的数量')
      //     return
      //   }
      // }
      this.subLoading = true
      inventoryAdd({
        param: {
          goodsList: this.addGoodsList,
          type: '3',
          info: this.remark,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.subLoading = false
          if (res.errorCode !== '000000') return
          this.$message.success('销毁成功')
          this.showPutStorageAdd = false
          this.clearPutStorageInfo()
          this.getList(1)
        })
        .catch(() => {
          this.subLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-item {
  .add-item-header {
    display: flex;
    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }
    .content {
      .barcode {
        margin-left: 10px;
        width: 200px;
      }
      .goods {
        margin-left: 10px;
        width: 150px;
      }
      .num {
        margin-left: 10px;
        margin-right: 20px;
        width: 90px;
      }
    }
  }
  .add-item-goods {
    display: flex;
    margin-top: 10px;
    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }
    .content {
      .barcode {
        margin-left: 10px;
        width: 200px;
      }
      .goods {
        margin-left: 10px;
        width: 150px;
      }
      .num {
        margin-left: 10px;
        margin-right: 20px;
        width: 90px;
      }
    }
  }
  .add-item-footer {
    display: flex;
    margin-top: 10px;
    .title {
      width: 90px;
      display: inline-block;
      word-wrap: break-word;
      white-space: normal;
      line-height: 40px;
      height: 40px;
      text-align: right;
    }
    .content {
      width: 81%;
      .remark {
        margin-left: 10px;
      }
    }
  }
}
</style>
